use std::collections::HashMap;

use crate::mapper::{self};
use crate::utils::http;
use sea_orm::{ActiveValue, DatabaseConnection};
use serde::Deserialize;
use sky_common::constant::message;
use sky_common::constant::{self, status, user::WX_LOGIN};
use sky_pojo::entities::user;
use sky_pojo::{dto::user::UserLoginDTO, entities::user::Model};

#[derive(Debug, Deserialize)]
struct OpenId {
    openid: String,
}

#[derive(Debug, Deserialize)]
struct WxLoginFallback {
    pub openid: String,
    pub session_key: String,
    pub unionid: String,
    pub errcode: i8,
    pub errmsg: String,
}
pub async fn get_openid(code: String) -> Result<String, String> {
    let appid = dotenv::var("wechat.appid").unwrap();
    let secret = dotenv::var("wechat.secret").unwrap();
    let mut map = HashMap::<&str, &str>::new();
    map.insert("appid", &appid);
    map.insert("secret", &secret);
    map.insert("js_code", &code);
    map.insert("grant_type", "authorization_code");
    println!("{:?}", map);

    match http::do_get::<WxLoginFallback>(constant::user::WX_LOGIN, Some(map)).await {
        Ok(fb) => return Ok(fb.openid),
        Err(e) => return Err(e.to_string()),
    };
}

pub async fn wechat_login(db: DatabaseConnection, dto: UserLoginDTO) -> Result<Model, String> {
    let openid = dto.code;
    // let openid = match get_openid(dto.code).await {
    //     Ok(id) => id,
    //     Err(e) => {
    //         tracing::error!("{}", e);
    //         "".to_owned()
    //     }
    // };

    // if openid.is_empty() {
    //     return Err(constant::message::LOGIN_FAILED.to_string());
    // }

    let result = mapper::user::get_by_openid(db.clone(), openid.clone()).await;

    match result {
        Ok(None) => {
            let new_user_model = user::ActiveModel {
                openid: ActiveValue::set(Some(openid.clone())),
                ..Default::default()
            };

            match mapper::user::sign_up(db.clone(), new_user_model).await {
                Ok(model) => Ok(model),
                Err(_) => Err("注册绑定失败".to_string()),
            }
        }
        Ok(Some(model)) => Ok(model),
        Err(e) => Err(e.to_string()),
    }
}
